package com.bwt.top.bwt_ad_flutter.manager;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;

import androidx.annotation.NonNull;

import com.bwt.top.bwt_ad_flutter.AdErrorUtil;
import com.bwt.top.bwt_ad_flutter.ad.BwtBannerAd;
import com.bwt.top.bwt_ad_flutter.ad.BwtInterstitialAd;
import com.bwt.top.bwt_ad_flutter.config.BwtAdEventConfig;
import com.bwt.top.bwt_ad_flutter.listener.OnAdReleaseListener;
import com.bwt.top.bwt_ad_flutter.model.AdParams;
import com.bwt.top.bwt_ad_flutter.util.LogUtil;
import com.bwt.top.bwt_ad_flutter.view.factory.BwtBannerAdFactory;
import com.bwt.top.bwt_ad_flutter.view.factory.BwtNativeExpressAdFactory;
import com.bwt.top.exception.AdError;

import java.util.HashMap;
import java.util.Map;

/**
 * banner广告管理器
 * **/
public class BwtBannerAdManager implements OnAdReleaseListener {

    private static BwtBannerAdManager instance;

    private final Map<String,BwtBannerAd> bwtBannerAdMap = new HashMap<>();

    //构造器
    private BwtBannerAdManager(){
        BwtAdManager.getInstance().registerOnAdReleaseListener(this);
    }

    public static BwtBannerAdManager getInstance(){
        if (instance == null){
            synchronized (BwtBannerAdManager.class){//同步代码
                if (instance == null){
                    instance = new BwtBannerAdManager();//创建对象
                }
            }
        }
        return instance;
    }

    public void loadBannerAd(Context context, @NonNull AdParams adParams,boolean loadThenShow){
        LogUtil.log("banner广告加载预备,adId: " + adParams.getAdId());
        if (!(context instanceof Activity) || (((Activity) context).isFinishing())){
            LogUtil.log("banner广告加载失败,adId "+adParams.getAdId()+",error: 当前上下文不适合获取banner广告!");
            BwtAdManager.getInstance().postAdEvent(BwtAdEventConfig.KEY_AD_EVENT_ON_AD_FAILED,adParams, AdErrorUtil.getError(new AdError(-1, "当前上下文不适合获取信息流广告")));
            return;
        }
        BwtBannerAd bwtBannerAd = new BwtBannerAd(adParams,(Activity) context);
        bwtBannerAdMap.put(adParams.getAdId(),bwtBannerAd);
        bwtBannerAd.loadAd();
    }



    @Override
    public void onAdRelease(String adId) {
        release(adId);
    }

    /**
     * 释放广告
     */
    private void release(String adId) {
        if (adId == null) return;
        try {
            BwtBannerAd bwtBannerAd = bwtBannerAdMap.get(adId);
            if (bwtBannerAd != null) {
                bwtBannerAd.release();
                bwtBannerAdMap.remove(adId);
            }
            BwtBannerAdFactory factory = BwtAdManager.getInstance().getBwtBannerAdFactory();
            if (factory != null) factory.release(adId);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public Map<String, BwtBannerAd> getBwtBannerAdMap() {
        return bwtBannerAdMap;
    }
}
